package com.red.star.wechat.work.site.banner;


import com.red.star.wechat.data.entity.BannerExpand;
import com.red.star.wechat.data.entity.Mall;
import com.red.star.wechat.data.entity.MallCity;
import com.red.star.wechat.data.entity.SysParam;
import com.red.star.wechat.data.mappers.BannerMapper;
import com.red.star.wechat.data.mappers.MallMapper;
import com.red.star.wechat.data.utils.CheckUtil;
import com.red.star.wechat.data.utils.DateUtil;
import com.red.star.wechat.data.utils.FileUtil;
import com.red.star.wechat.data.utils.TicketUtil;
import com.red.star.wechat.work.constant.AdminSessionHolder;
import com.red.star.wechat.work.constant.Constant;
import com.red.star.wechat.work.entity.Admin;
import com.red.star.wechat.work.entity.TableContainer;
import com.red.star.wechat.work.utils.BeanUtil;
import com.red.star.wechat.work.utils.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;
import tk.mybatis.mapper.util.StringUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: banner管理
 * @Author: liucancan
 * @Date: 2018/9/26
 */
@RestController
@RequestMapping("/work")
public class BannerManageController {

    @Autowired
    private BannerService bannerService;

    @Resource
    private BannerMapper bannerMapper;

    @Resource
    private MallMapper mallMapper;

    /**
     * @Description: banner模板管理页面
     * @Param: []
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: liucancan
     * @Date: 2018/9/26
     */
    @RequestMapping("/bannerManage")
    public ModelAndView bannerManage() {
        Admin admin = AdminSessionHolder.get();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("bannermanage");
        try {
            String token = FileUtil.fetchToken(SysParam.MACALLINE_FILE_EMPLOYEE_ID);
            if (CheckUtil.isEmpty(token)) {
                token = "";
            }
            // 集团登录城市下商场
            if (StringUtils.isEmpty(admin.getMallCode())) {
                List<MallCity> cityContaiMall = mallMapper.findCityContaiMall();
                modelAndView.addObject("cityContaiMall", cityContaiMall);
            } else {
                modelAndView.addObject("posterObj", TicketUtil.postList(mallMapper.getMallByMallCode(admin.getMallCode()).getOmsCode()));
            }
            List<Mall> mallList = mallMapper.findMallsByMallCode(admin.getMallCode());
            modelAndView.addObject("admin", admin);
            modelAndView.addObject("token", token);
            modelAndView.addObject("mallList", mallList);
        } catch (Exception e) {
            System.out.println("获取token异常");
        }
        modelAndView.addObject("fileUploadUrl", SysParam.MACALLINE_FILE_UPLOAD_URL);
        return modelAndView;
    }

    /**
     * @Description: banner管理列表
     * @Param: [bannerTeamplate]
     * @return: org.springframework.http.ResponseEntity<?>
     * @Author: liucancan
     * @Date: 2018/9/27
     */
    @RequestMapping(value = "listBanner")
    public ResponseEntity listTestData(BannerExpand bannerExpand) {
        Admin admin = AdminSessionHolder.get();
        bannerExpand.setMallCode(admin.getMallCode());
        if (!CheckUtil.isEmpty(bannerExpand.getBannerStartTime())) {
            bannerExpand.setStartTime(DateUtil.getDateAsYYYYMMDD(bannerExpand.getBannerStartTime()));
        }
        if (!CheckUtil.isEmpty(bannerExpand.getBannerEndTime())) {
            bannerExpand.setEndTime(DateUtil.getDateAsYYYYMMDD(bannerExpand.getBannerEndTime()));
            Date endTime = DateUtil.getDateAsYYYYMMDD(bannerExpand.getBannerEndTime());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(endTime);
            calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH),
                    23, 59, 59);
            bannerExpand.setEndTime(calendar.getTime());
        }
        TableContainer bannerTable = bannerService.findBanner(bannerExpand);
        return new ResponseEntity<>(bannerTable, HttpStatus.OK);
    }

    /**
     * @Description: 添加banner
     * @Param: [bannerExpand]
     * @return: org.springframework.http.ResponseEntity<?>
     * @Author: liucancan
     * @Date: 2018/9/29
     */
    @RequestMapping(value = "addBanner")
    public ResponseEntity addBanner(BannerExpand bannerExpand) {
        // 微信H5链接时判断是否可用
        if (null != bannerExpand.getLinkType() && 2 == bannerExpand.getLinkType()) {
            String url = bannerExpand.getLink();
            url = ((url.substring(0, 7).toLowerCase().equals("http://")) ? url.replace("http://", "https://") : ((url.substring(0, 8).toLowerCase().equals("https://"))) ? url : "https://" + url);
            bannerExpand.setLink(url);
            String[] h5urls = SysParam.MINI_PROGRAM_H5_URL.split(",");
            Matcher matcherOne = Pattern.compile("^([hH][tT]{2}[pP]://|[hH][tT]{2}[pP][sS]://)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+$").matcher(bannerExpand.getLink());
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("msg", "H5链接不可用,");
            if (matcherOne.find()) {
                Matcher matcherTwo = Pattern.compile("[^//]*?\\.(com|cn|net|org|biz|info|cc|tv)").matcher(bannerExpand.getLink());
                boolean contains;
                if (matcherTwo.find()) {
                    contains = Arrays.asList(h5urls).contains(matcherTwo.group());
                    if (!contains) {
                        return new ResponseEntity(resultMap, HttpStatus.OK);
                    }
                } else {
                    return new ResponseEntity(resultMap, HttpStatus.OK);
                }
            } else {
                return new ResponseEntity(resultMap, HttpStatus.OK);
            }
        }
        Admin admin = AdminSessionHolder.get();
        bannerExpand.setMallCode(admin.getMallCode());
        if (!CheckUtil.isEmpty(bannerExpand.getBannerStartTime())) {
            bannerExpand.setStartTime(DateUtil.getDateAsYYYYMMDD(bannerExpand.getBannerStartTime()));
        }
        if (!CheckUtil.isEmpty(bannerExpand.getBannerEndTime())) {
            Date endTime = DateUtil.getDateAsYYYYMMDD(bannerExpand.getBannerEndTime());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(endTime);
            calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                    calendar.get(Calendar.DAY_OF_MONTH),
                    23, 59, 59);
            bannerExpand.setEndTime(calendar.getTime());
        }
        ResponseEntity result;
        try {
            result = bannerService.addBanner(bannerExpand);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(false, HttpStatus.BAD_REQUEST);
        }
        return result;
    }

    /**
     * @Description: banner状态
     * @Param: [bannerExpand]
     * @return: org.springframework.http.ResponseEntity<?>
     * @Author: liucancan
     * @Date: 2018/9/29
     */
    @RequestMapping(value = "changeBannerStatus")
    public ResponseEntity changeBannerStatus(BannerExpand bannerExpand) {
        return bannerService.changeBannerStatus(bannerExpand);
    }

    /**
     * @Description: banner详情
     * @Param: [bannerExpand]
     * @return: org.springframework.http.ResponseEntity<?>
     * @Author: liucancan
     * @Date: 2018/9/29
     */
    @RequestMapping(value = "bannerInfo")
    public ResponseEntity bannerInfo(BannerExpand bannerExpand) {
        return bannerService.bannerInfo(bannerExpand);
    }

    /**
     * @Description: banner下发
     * @Param: [bannerExpand]
     * @return: org.springframework.http.ResponseEntity<?>
     * @Author: liucancan
     * @Date: 2018/9/29
     */
    @RequestMapping(value = "sentDown")
    public ResponseEntity sentDown(BannerExpand bannerExpand) {
        return bannerService.sentDown(bannerExpand);
    }

    /**
     * @Description: bannerToExcel
     * @Param: [bannerExpand]
     * @return: org.springframework.http.ResponseEntity<?>
     * @Author: liucancan
     * @Date: 2018/9/29
     */
    @RequestMapping(value = "exportBannerExcel")
    public ResponseEntity exportBannerExcel(BannerExpand bannerExpand, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Admin admin = AdminSessionHolder.get();
        bannerExpand.setMallCode(admin.getMallCode());
        if (!CheckUtil.isEmpty(bannerExpand.getBannerStartTime())) {
            bannerExpand.setStartTime(DateUtil.getDateAsYYYYMMDD(bannerExpand.getBannerStartTime()));
        }
        if (!CheckUtil.isEmpty(bannerExpand.getBannerEndTime())) {
            bannerExpand.setEndTime(DateUtil.getDateAsYYYYMMDD(bannerExpand.getBannerEndTime()));
        }
        List<BannerExpand> banners = bannerMapper.findBanner(bannerExpand);
        List<Map<String, Object>> listMapBanner = new ArrayList<>();
        banners.forEach(bannerInfo -> {
            try {
                if (StringUtil.isEmpty(bannerInfo.getMallName())) {
                    bannerInfo.setMallName("集团");
                }
                bannerInfo.setStatusValue(0 == bannerInfo.getStatus() ? "待上架" : 1 == bannerInfo.getStatus() ? "已上架" : 2 == bannerInfo.getStatus() ? "已下架" : "已失效");
                // 处理连接
                if (null != bannerInfo.getLinkType()) {
                    if (bannerInfo.getLinkType() == 1) { // 海报
                        bannerInfo.setLink("海报ID:" + bannerInfo.getPosterId() + "\r\n" + "海报类型:" + bannerInfo.getPosterType() + "\r\n" + "海报名称:" + bannerInfo.getPosterName());
                    } else if (bannerInfo.getLinkType() == 2) { // 微信H5
                        bannerInfo.setLink("微信H5:" + bannerInfo.getLink());
                    } else { // 小程序
                        bannerInfo.setLink("APPID:" + bannerInfo.getAppId() + "\r\n" + "小程序路径:" + bannerInfo.getLink());
                    }
                }
                Map<String, Object> bannerMap = BeanUtil.transBean2Map(bannerInfo);
                bannerMap.put("bannerTime", DateUtil.getDateAsYYYY_MM_DD(bannerInfo.getStartTime()) + "~" + DateUtil.getDateAsYYYY_MM_DD(bannerInfo.getEndTime()));
                bannerMap.put("createBannerTime", DateUtil.getDateAsYYYY_MM_DD_HHMMSS(bannerInfo.getCreateTime()));
                listMapBanner.add(bannerMap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        int[] ds_format = {1, 1, 1, 1, 1, 1, 1};
        ExcelUtils.export(Constant.BANNER_MANAGE_TITLE, Constant.BANNER_MANAGE_SHEET_1, Constant.BANNER_MANAGE_COLUNM.split(","), Constant.BANNER_MANAGE_FIELD.split(","), ds_format, null, listMapBanner, request, response);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * @Description:编辑待上架的banner
     * @Param: [bannerExpand]
     * @return: org.springframework.http.ResponseEntity
     * @Author: liucancan
     * @Date: 2018/10/30
     */
    @RequestMapping(value = "editBanner")
    public ResponseEntity editBanner(BannerExpand bannerExpand) {
        return bannerService.editBanner(bannerExpand);
    }

}
